﻿using Application.Common.Interfaces;
using Common.Enums;
using Common.Hubs;
using Common.Interfaces;
using Common.MessageTemplates;
using Common.Models;
using Common.Utils;
using Domain.Entities.Identity;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Application.Features.Users.EventHandlers;


public class UpdateUserAvatarEvent<T> : DomainEvent
{
    public UpdateUserAvatarEvent(T entity)
    {
        Entity = entity;
    }

    public T Entity { get; }
}


public class UpdateUserAvatarEventHandler : INotificationHandler<UpdateUserAvatarEvent<User>>
{
    private readonly ILogger<UpdateUserAvatarEventHandler> _logger;
    private readonly IServiceProvider _serviceProvider;
    private readonly IHubContext<SignalRHub> _hubContext;
    private readonly ICurrentUserService _currentUserService;

    public UpdateUserAvatarEventHandler(
        ILogger<UpdateUserAvatarEventHandler> logger,
        IServiceProvider serviceProvider,
        IHubContext<SignalRHub> hubContext,
        ICurrentUserService currentUserService)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
        _hubContext = hubContext;
        _currentUserService = currentUserService;
    }

    public Task Handle(UpdateUserAvatarEvent<User> notification, CancellationToken cancellationToken)
    {
        var isMyself = _currentUserService.CurrentUserId == notification.Entity.Id;
        if (isMyself) return Task.CompletedTask;

        using (var scope = _serviceProvider.CreateScope())
        {
            var _context = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
            if (!_context.Roles.Any()) return Task.CompletedTask;

            var receiveMessageUsers = _context.Users.ToList();
            if (!receiveMessageUsers.Any()) return Task.CompletedTask;

            Random random = new Random();
            SignalRMessageTemplate signalRMessageTemplate = new SignalRMessageTemplate()
            {
                Id = random.Next(999999999),
                MessageType = MessageType.UpdataUserAvatar,
                Content = $"你的头像发生了改变",
                Username = notification.Entity.UserName!
            };
            _hubContext.Clients.User(notification.Entity.Id.ToString()).SendAsync("ReceivePrivateMessage", signalRMessageTemplate.ToJson(true, true));
            _logger.LogDebug($"发送通知：{nameof(MessageType.UpdataUserAvatar)}");
        }
        return Task.CompletedTask;
    }
}